package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mon-go-web/pkg/logger"
	"mon-go-web/pkg/response"
	"net/http"
)

func ErrorMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		ctx.Next()

		if len(ctx.Errors) > 0 {
			for _, err := range ctx.Errors {
				logger.Logger.Error("Request failed", zap.Error(err))
				response.Error(ctx, http.StatusBadRequest, err.Error())
			}
		}
	}
}

func BindJSON(ctx *gin.Context, obj interface{}) bool {
	if err := ctx.ShouldBindJSON(obj); err != nil {
		ctx.Error(err)
		return false
	}
	return true
}
